#!/usr/bin/env python
# -*-coding:UTF-8 -*-
'''
@Project ：爬虫-波波老师
@File：22-用户中心的用户信息.py
@Author ：文非
@Date：2021/3/1219:54
@Require： 爬取用户中心页的用户信息 在模拟登录后 点击头像超链接 发送请求 获取数据
'''

import requests
from lxml import etree
from chaojiying import Chaojiying_Client

def define(username, pwd, itemid):
    """验证码识别"""
    chaojiying = Chaojiying_Client(username, pwd, itemid)  # 用户中心>>软件ID 生成一个替换 96001
    # chaojiying = Chaojiying_Client('zwwlx1013', 'zwwlx1013', '913953')  # 用户中心>>软件ID 生成一个替换 96001
    im = open('./rencode1.jpg', 'rb').read()  # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
    define_res = chaojiying.PostPic(im, 1902)['pic_str']
    print(define_res)
    return define_res

def main():
    # 创建session对象获取携带存储cookies

    session = requests.Session()

    headers = {
        'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"
    }
    url = "http://www.renren.com"
    response = requests.get(url=url, headers=headers)
    define_text = response.text
    tree = etree.HTML(define_text)
    define_url = tree.xpath('//*[@id="verifyPic_login"]/@src')[0]
    print(define_url)
    define_response = requests.get(url=define_url, headers=headers)
    define_data = define_response.content
    with open("./rencode1.jpg","wb")as fp:
        fp.write(define_data)
    username = 'zwwlx1013'
    pwd = 'zwwlx1013'
    itemid = '913953'
    result = define(username,pwd,itemid)
    print(result)
    login_url = "http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=2021251841290"
    data = {
        "email": "13476923553",
        "icode": "",
        "origURL": "http://www.renren.com/home",
        "domain": "renren.com",
        "key_id": "1",
        "captcha_type": "web_login",
        "password": "5b44f3869e203e2510d8e45f1ba095f52fe82c615027c657b65f322286dc0e84",
        "rkey": "86854a257ebff1d95f0242cc03b67fa5",
        "f": "http%3A%2F%2Fwww.renren.com%2F975503334"
    }

    # 使用session进行post请求而不是用requests

    login_after_page = session.post(url=login_url, data=data, headers=headers).text
    login_after_page = login_after_page.split("\"")[5]
    home_url = login_after_page
    home_page_response = session.get(url=home_url,headers=headers)
    home_page = home_page_response.text
    response_code = home_page_response.status_code
    with open("./renren1.html", "w", encoding="utf-8")as fp:
        fp.write(home_page)
    tree_center = etree.HTML(home_page)
    center_url_wrong= tree_center.xpath('//div[@class="hd-wraper"]//div/dl/dt/a/@href')
    center_url = "http://www.renren.com/975503334/profile"
    center_page = requests.get(url=center_url, headers=headers).text
    with open("./人人个人中心1.html","w",encoding="utf-8")as fp:
        fp.write(center_page)


if __name__ == "__main__":

    main()
